package com.example.springboot_app.controller;

import com.example.springboot_app.dao.ILikesDao;
import com.example.springboot_app.dao.MyPostsDao;
import com.example.springboot_app.pojo.Likes;
import com.example.springboot_app.pojo.MyPosts;
import com.example.springboot_app.service.ILikesService;
import com.example.springboot_app.util.RedisUtils;
import com.example.springboot_app.vo.ResponseMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/myposts")
public class MyPostsController {
    @Autowired
    MyPostsDao myPostsDao;
    @Autowired
    ILikesService likesService;
    @Autowired
    RedisUtils redisUtils;
    @RequestMapping("/get")
    List<MyPosts> get(){
        List<MyPosts> list=myPostsDao.getAllPostsWithDetails();
        System.out.println("myposts:"+list);
        return myPostsDao.getAllPostsWithDetails();
    }
    @RequestMapping("addLikes")
    ResponseMsg addLikes(Integer id){
        Double value= redisUtils.zscore("likes", id);
        Double count=(value!=null)? value+1:0;
        redisUtils.zset("likes",id, count);
        return ResponseMsg.success("点赞成功");
    }
    @Scheduled(fixedDelay = 5000)
    ResponseMsg update() {
        Set< ZSetOperations.TypedTuple<Object>> postsSet=
                redisUtils.zreverseRangeWithScores("likes",0,-1);
        System.out.println(postsSet);
        for(ZSetOperations.TypedTuple<Object> t:postsSet){
            Integer id= (Integer) t.getValue();
            Double value=t.getScore();
            Likes likes=likesService.getById(id);
            if(likes!=null){
                likes.setCount(value.intValue());
                likesService.updateById(likes);
                System.out.println(id+"更新后的点赞数为："+likes.getCount());
            }
        }
        return ResponseMsg.success("修改成功");
    }
}
